package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vehiclemanagement.entity.ETCCard;
import com.vehiclemanagement.service.ETCCardService;
import com.vehiclemanagement.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ETC卡信息管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/etccard")
public class ETCCardController {

    @Autowired
    private ETCCardService etcCardService;

    /**
     * 分页查询ETC卡列表
     *
     * @param page       页码
     * @param pageSize   每页记录数
     * @param cardNumber 卡号搜索关键词
     * @param type       卡类型搜索关键词
     * @param status     状态搜索关键词
     * @param vehiclePlateNumber 车牌号搜索关键词
     * @return 分页查询结果
     */
    @GetMapping("/list")
    public Result<Page<ETCCard>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "cardNumber", required = false) String cardNumber,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "vehiclePlateNumber", required = false) String vehiclePlateNumber) {
        log.info("分页查询ETC卡信息，页码：{}，每页记录数：{}，卡号关键词：{}，卡类型：{}，状态：{}，车牌号：{}", 
                 page, pageSize, cardNumber, type, status, vehiclePlateNumber);

        // 创建分页对象
        Page<ETCCard> pageInfo = new Page<>(page, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<ETCCard> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加卡号搜索条件
        if (StringUtils.hasText(cardNumber)) {
            queryWrapper.like(ETCCard::getCardNumber, cardNumber);
        }
        
        // 添加卡类型搜索条件
        if (StringUtils.hasText(type)) {
            queryWrapper.eq(ETCCard::getType, type);
        }
        
        // 添加状态搜索条件
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(ETCCard::getStatus, status);
        }
        
        // 添加车牌号搜索条件
        if (StringUtils.hasText(vehiclePlateNumber)) {
            queryWrapper.like(ETCCard::getVehiclePlateNumber, vehiclePlateNumber);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(ETCCard::getCreateTime);

        // 执行查询
        etcCardService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);
    }

    /**
     * 根据ID获取ETC卡详情
     *
     * @param id ETC卡ID
     * @return ETC卡详情
     */
    @GetMapping("/{id}")
    public Result<ETCCard> getById(@PathVariable Long id) {
        log.info("获取ETC卡详情，ID：{}", id);
        ETCCard etcCard = etcCardService.getById(id);
        if (etcCard != null) {
            return Result.success(etcCard);
        }
        return Result.error("未找到该ETC卡信息");
    }

    /**
     * 添加ETC卡
     *
     * @param etcCard ETC卡信息
     * @return 添加结果
     */
    @PostMapping
    public Result<String> add(@RequestBody ETCCard etcCard) {
        log.info("添加ETC卡信息：{}", etcCard);
        
        // 检查卡号是否已存在
        LambdaQueryWrapper<ETCCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ETCCard::getCardNumber, etcCard.getCardNumber());
        long count = etcCardService.count(queryWrapper);
        if (count > 0) {
            return Result.error("卡号已存在，请勿重复添加");
        }
        
        boolean success = etcCardService.save(etcCard);
        if (success) {
            return Result.success("ETC卡信息添加成功");
        } else {
            return Result.error("ETC卡信息添加失败");
        }
    }

    /**
     * 更新ETC卡信息
     *
     * @param etcCard ETC卡信息
     * @return 更新结果
     */
    @PutMapping
    public Result<String> update(@RequestBody ETCCard etcCard) {
        log.info("更新ETC卡信息：{}", etcCard);
        
        if (etcCard.getId() == null) {
            return Result.error("ETC卡ID不能为空");
        }
        
        // 检查卡号是否与其他卡重复
        LambdaQueryWrapper<ETCCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ETCCard::getCardNumber, etcCard.getCardNumber())
                   .ne(ETCCard::getId, etcCard.getId());
        long count = etcCardService.count(queryWrapper);
        if (count > 0) {
            return Result.error("卡号已存在，请使用其他卡号");
        }
        
        boolean success = etcCardService.updateById(etcCard);
        if (success) {
            return Result.success("ETC卡信息更新成功");
        } else {
            return Result.error("ETC卡信息更新失败，请检查ID是否存在");
        }
    }

    /**
     * 删除ETC卡（物理删除）
     *
     * @param id ETC卡ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        log.info("删除ETC卡信息，ID：{}", id);
        
        boolean success = etcCardService.removeById(id);
        if (success) {
            log.info("ETC卡信息删除成功，ID：{}", id);
            return Result.success("ETC卡信息已删除");
        } else {
            log.error("ETC卡信息删除失败，ID：{}", id);
            return Result.error("ETC卡信息删除失败，请检查ID是否存在");
        }
    }

    /**
     * 获取所有卡类型
     *
     * @return 卡类型列表
     */
    @GetMapping("/cardTypes")
    public Result getCardTypes() {
        try {
            List<String> cardTypes = etcCardService.getCardTypes();
            if (cardTypes != null && !cardTypes.isEmpty()) {
                return Result.success(cardTypes);
            } else {
                return Result.error("获取卡类型列表失败");
            }
        } catch (Exception e) {
            log.error("获取ETC卡类型时出错: {}", e.getMessage(), e);
            return Result.error("获取卡类型时发生错误: " + e.getMessage());
        }
    }

    /**
     * 获取所有卡状态
     *
     * @return 卡状态列表
     */
    @GetMapping("/statusTypes")
    public Result getStatusTypes() {
        try {
            List<String> statusTypes = etcCardService.getStatusTypes();
            if (statusTypes != null && !statusTypes.isEmpty()) {
                return Result.success(statusTypes);
            } else {
                return Result.error("获取状态类型列表失败");
            }
        } catch (Exception e) {
            log.error("获取ETC卡状态类型时出错: {}", e.getMessage(), e);
            return Result.error("获取状态类型时发生错误: " + e.getMessage());
        }
    }

    /**
     * 检查卡号是否存在
     *
     * @param cardNumber 卡号
     * @param excludeId  排除的ID
     * @return 检查结果
     */
    @GetMapping("/check")
    public Result<Map<String, Object>> checkCardNumber(@RequestParam String cardNumber, 
                                                      @RequestParam(required = false) Long excludeId) {
        log.info("检查ETC卡号是否存在：{}，排除ID：{}", cardNumber, excludeId);
        
        LambdaQueryWrapper<ETCCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ETCCard::getCardNumber, cardNumber);
        
        if (excludeId != null) {
            queryWrapper.ne(ETCCard::getId, excludeId);
        }
        
        List<ETCCard> existingCards = etcCardService.list(queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("exists", !existingCards.isEmpty());
        result.put("records", existingCards);
        
        return Result.success(result);
    }

    /**
     * 测试API是否正常工作
     *
     * @return 测试结果
     */
    @GetMapping("/test")
    public String test() {
        return "ETC卡管理API工作正常";
    }
} 